import java.util.Stack;

/**
 * 面试题 16.26. 计算器
 * https://leetcode-cn.com/problems/calculator-lcci/
 */
public class Solutions_mianshi_16_26 {
    public static void main(String[] args) {
        String str = "3+2*2";  // output: 7
//        String str = " 3/2 ";  // output: 1
//        String str = " 3+5 / 2 ";  // output: 5
//        String str = "42";  // output: 42

        int result = calculate(str);
        System.out.println(result);
    }

    public static int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        char[] sarr = s.toCharArray();
        char opt = '+';
        int num = 0;

        for (int i = 0; i < sarr.length; i++) {
            char c = sarr[i];
            if (Character.isDigit(c)) {
                // 是数字
                num = num * 10 + (c - '0');
                if (i != sarr.length - 1 && Character.isDigit(sarr[i + 1])) {
                    continue;
                }
                if (opt == '+') {
                    stack.push(num);
                } else if (opt == '-') {
                    stack.push(-num);
                } else if (opt == '*') {
                    num = stack.pop() * num;
                    stack.push(num);
                } else {
                    num = stack.pop() / num;
                    stack.push(num);
                }
            } else if (c == ' ') {
                // num 置 0
                num = 0;
                continue;
            } else {
                // 记录下下一数字的运算符，num 置 0
                opt = c;
                num = 0;
            }
        }
        int res = 0;
        while (!stack.isEmpty()) {
            // stack 中的元素相加
            res += stack.pop();
        }
        return res;
    }
}
